package com.kaibes.module.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.kaibes.core.base.options.BooleanOptions;
import com.kaibes.module.apilink.ApiLinkService;
import com.kaibes.module.permission.db.service.PermissionService;
import com.kaibes.module.permission.db.service.PowerService;
import com.kaibes.module.user.UserService;

@Component
public class PermissionCheckerImpl implements PermissionChecker {

    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private ApiLinkService apiLinkService;
    @Autowired
    private PowerService powerService;
    
    public boolean needPermission(String url, String method) {
        return permissionService.isEnable(apiLinkService.findPermissionId(url, method));
    }
    
    public boolean hasPermission(Integer userId, String url, String method) {
        if (userId == 1) {
            //the first user does not need any permission.
            return true;
        }
        
        Integer permissionId = apiLinkService.findPermissionId(url, method);
        return BooleanOptions.returnTrue(permissionService.isEnable(permissionId), 
                ()->powerService.has(userService.findRoleIdById(userId), permissionId));
    }
    
    
}
